package com.gc.cscott.cli;

import com.gc.cscott.domain.contest.Contest;
import com.gc.cscott.domain.contest.Source;
import com.gc.cscott.fs.FileSystemWorker;
import com.gc.cscott.util.CscottUtil;
import com.google.inject.Inject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author root
 */
public class BackupCommand implements Command {
    @Inject
    FileSystemWorker fsWorker;

    @Inject
    Contest contest;

    public List<String> listHelp() {
        return Arrays.asList("Packs solutions, contest and results directories into",
                "archive which will be named 'backup-<date>.zip'",
                "and placed into current directory");
    }

    public List<String> perform(List<String> args) {
        try {
            File outputFile = new File("backup-" + CscottUtil.currentTimeString() + ".zip");
            ZipOutputStream zipOutput = new ZipOutputStream(new FileOutputStream(outputFile));
            for (Source source : contest.getSourcesList()) {
                packDirectory(zipOutput, source.getLocationDir());
            }
            packDirectory(zipOutput, new File(contest.getTaskDir()));
            packDirectory(zipOutput, new File(contest.getResultDir()));
            zipOutput.flush();
            zipOutput.close();
            System.out.println("Backup file: "+outputFile.getName());
            return args;
        } catch (IOException ex) {
            throw new Error(ex);
        }
    }

    protected void packDirectory(ZipOutputStream zipOutput, File dir) throws IOException {
        for (File file : fsWorker.listFilesAll(dir)) {
            if (file.isFile() == true) {
                zipOutput.putNextEntry(new ZipEntry(file.getPath()));
                zipOutput.write(FileUtils.readFileToByteArray(file));
                zipOutput.closeEntry();
                System.out.println("   added file: "+file.getPath());
            }
        }
        System.out.println("  resource packed: " + dir.getPath());

    }
}
